import { createApp, isVNode } from 'vue'
import directives from '@/directives/index.js'
import { nanoid } from 'nanoid'

function createEl(id, content) {
  let el = document.getElementById(id)
  if (!el) {
    el = document.createElement('div')
    el.setAttribute('id', id)
  }
  isVNode(content) ? render(content, el) : (el.innerHTML = content)
  return el
}

function _createPopup(app, el) {
  let visible = true

  const show = () => {
    visible = true
    el.style.display = 'block'
  }

  const hide = () => {
    visible = false
    el.style.display = 'none'
  }

  const destroy = () => {
    app.unmount()
    document.body.removeChild(el)
  }

  return {
    app,
    el,
    get visible() {
      return visible
    },
    show,
    hide,
    destroy,
  }
}

function nominalmount(component, options = {}) {
  let id = options.id || nanoid()
  return createEl(id, component)
}

export function createPopup(component, props, options) {
  const el = nominalmount(component, options)
  const app = createApp(component, props).use(directives)
  app.mount(el)
  document.body.appendChild(el)
  return _createPopup(app, el)
}
